package org.eclipse.iota;

import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Plugin;
import org.eclipse.core.runtime.Status;
import org.eclipse.iota.rewrite.IotaRule;
import org.eclipse.iota.rewrite.IotaRuleManager;
import org.osgi.framework.BundleContext;

/**
 * @author Christian Krause
 * @generated NOT
 */
public class IotaPlugin extends Plugin {
	
	// Plug-in ID.
	public static final String PLUGIN_ID = "org.eclipse.iota.core";
	
	// Plug-in instance.
	private static IotaPlugin instance;
	
	/**
	 * Default constructor.
	 */
	public IotaPlugin() {
		super();
	}
	
	/*
	 * (non-Javadoc)
	 * @see org.eclipse.core.runtime.Plugin#start(org.osgi.framework.BundleContext)
	 */
	@Override
	public void start(BundleContext context) throws Exception {
		super.start(context);
		instance = this;
		
		// Load rule extensions.
		IExtensionRegistry registry = Platform.getExtensionRegistry();
		IExtensionPoint point = registry.getExtensionPoint(PLUGIN_ID + ".rules");
		IConfigurationElement[] elements = point.getConfigurationElements();
		for (int i=0;i<elements.length; i++) {
			if (elements[i].getName().equals("rule")) {				
				IotaRule rule = (IotaRule) elements[i].createExecutableExtension("class");
				if (rule==null) {
					logError("Error loading rule " + elements[i].getAttribute("id"), null);
					continue;
				}
				if (!IotaRuleManager.INSTANCE.getRuleTypes().contains(rule.getClass())) {
					IotaRuleManager.INSTANCE.getRuleTypes().add(rule.getClass());
				}
			}
		}
	}
	
	/*
	 * (non-Javadoc)
	 * @see org.eclipse.core.runtime.Plugin#stop(org.osgi.framework.BundleContext)
	 */
	@Override
	public void stop(BundleContext context) throws Exception {
		instance = null;
		super.stop(context);
	}
	
	public static IotaPlugin getInstance() {
		return instance;
	}
	
	public void logError(String error, Throwable throwable) {
		if (error == null && throwable != null) {
			error = throwable.getMessage();
		}
		getLog().log(new Status(IStatus.ERROR, PLUGIN_ID, IStatus.OK, error, throwable));
	}
	
	public void logInfo(String message) {
		getLog().log(new Status(IStatus.INFO, PLUGIN_ID, IStatus.OK, message, null));
	}
	
}
